import tool from '@/utils/tool'
import {ElNotification} from 'element-plus';
import config from "@/config"
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import useUserStore from "@/store/modules/user";
import router,{routes_404} from './router'
import {beforeEach, afterEach} from './router/scrollBehavior'
import pinia from '@/store'

const whiteList = ['login', 'doc', 'interfaceList', 'interfaceCode', 'signature', 'test']
const defaultRoutePath = '/dashboard'
const userStore = useUserStore(pinia)
//console.log(userStore)
//设置标题
document.title = config.APP_NAME

// NProgress配置
NProgress.configure({ showSpinner: false })

router.beforeEach(async (to, from, next) => {

	NProgress.start()


	//动态标题
	document.title = to.meta.title ? `${to.meta.title} - ${config.APP_NAME}` : `${config.APP_NAME}`

	let token = tool.data.get('token');

	if (token && token !== 'undefined') {

		//整页路由处理
		if (to.meta.fullpage) {
			to.matched = [to.matched[to.matched.length - 1]]
		}

		if (tool.data.get('lockScreen') && to.name !== 'lockScreen') {
			next({name: 'lockScreen'})
		} else if (!tool.data.get('lockScreen') && to.name === 'lockScreen') {
			next({path: defaultRoutePath})
		} else if (to.name === 'login') {
			next({path: defaultRoutePath})
		} else if (!userStore.routers) {
			await userStore.getUserInfo().then(res => {
				if (res.routers.length !== 0) {
					let routers = res.routers
					const apiRouter = flatAsyncRoutes(routers)
					apiRouter.forEach(item => {
						router.addRoute("layout", item)
					})
					router.addRoute(routes_404)
					if (to.matched.length == 0) {
						router.push(to.fullPath)
					}
				}
			}).catch(() => {
				next({name: 'login', query: {redirect: to.fullPath}})
				userStore.SET_ROUTERS(undefined)
				tool.data.clear()
			})
			beforeEach(to, from)
			next()
		} else {
			beforeEach(to, from)
			next()
		}
	} else {
		if (whiteList.includes(to.name)) {
			beforeEach(to, from)
			next()
		} else {
			next({name: 'login', query: {redirect: to.fullPath}})
		}
	}
});

router.afterEach((to, from) => {
	afterEach(to, from)
	NProgress.done()
});

router.onError((error) => {
	NProgress.done();
	const pattern = /Loading chunk (\d)+ failed/g;
	const isChunkLoadFailed = error.message.match(pattern);
	console.log(error)
	ElNotification.error({title: '路由错误', message: '路由未定义或路由页面不存在'});
	// const targetPath = router.history.pending.fullPath;
	// if (isChunkLoadFailed) {
	// 	router.replace(targetPath);
	// }
});

//路由扁平化
function flatAsyncRoutes(routes, breadcrumb = []) {
	let res = []
	routes.forEach(route => {
		const tmp = {...route}
		if (tmp.children) {
			let childrenBreadcrumb = [...breadcrumb]
			childrenBreadcrumb.push(route)
			let tmpRoute = {...route}
			tmpRoute.meta.breadcrumb = childrenBreadcrumb
			delete tmpRoute.children
			res.push(tmpRoute)
			let childrenRoutes = flatAsyncRoutes(tmp.children, childrenBreadcrumb)
			childrenRoutes.map(item => {
				res.push(item)
			})
		} else {
			let tmpBreadcrumb = [...breadcrumb]
			tmpBreadcrumb.push(tmp)
			tmp.meta.breadcrumb = tmpBreadcrumb
			res.push(tmp)
		}
	})
	return res
}
